package com.lp.typeHandler;

import java.sql.Array;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

public class StringListTypeHander implements TypeHandler<ArrayList<String>> {

	@Override
	public void setParameter(PreparedStatement ps, int i,
			ArrayList<String> parameter, JdbcType jdbcType) throws SQLException {
		Connection con = ps.getConnection();
        // hack: if using poolable connection from dbcp must get inside true connection! 
        if(con instanceof org.apache.commons.dbcp2.PoolableConnection ) {
            con =     ((org.apache.commons.dbcp2.PoolableConnection)con).getInnermostDelegate();
        }
        if(parameter!=null){
	        Array array = con.createArrayOf("varchar", parameter.toArray());
	        ps.setArray(i,array);
        }else
        	ps.setArray(i,null);

	}

	@Override
	public ArrayList<String> getResult(ResultSet rs, String columnName)
			throws SQLException {
		Array array = rs.getArray(columnName);
	    if (array != null) {
	    	ArrayList<String> data=new ArrayList<String>();
	    	for (Object object : (Object[])array.getArray()) {
				data.add((String)object);
			}
	      return data;
	    }
	    return null;
	}

	@Override
	public ArrayList<String> getResult(ResultSet rs, int columnIndex)
			throws SQLException {
		Array array = rs.getArray(columnIndex);
	    if (array != null) {
	    	ArrayList<String> data=new ArrayList<String>();
	    	for (Object object : (Object[])array.getArray()) {
				data.add((String)object);
			}
	      return data;
	    }
	    return null;
	}

	@Override
	public ArrayList<String> getResult(CallableStatement cs, int columnIndex)
			throws SQLException {
		Array array = cs.getArray(columnIndex);
	    if (array != null) {
	    	ArrayList<String> data=new ArrayList<String>();
	    	for (Object object : (Object[])array.getArray()) {
				data.add((String)object);
			}
	      return data;
	    }
	    return null;
	}
}
